import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;


public class ServletConfigDemo extends HttpServlet {
    //定义ServletConfig对象来接收配置的初始化参数
    private ServletConfig config;
    /*
      当servlet配置了初始化参数后，web容器在创建servlet实例对象时，
      会自动将这些初始化参数封装到ServletConfig对象中，并在调用servlet的init方法时，
      将ServletConfig对象传递给servlet。进而，程序员通过ServletConfig对象就可以
      得到当前servlet的初始化参数信息。
    */
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config =config;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取对象context
        ServletContext context = config.getServletContext();
        //获取共享数据
        Object nameValue = context.getAttribute("name");
        System.out.println(nameValue);
        System.out.println("---------");

        //根据参数名称获取值
        String name = config.getInitParameter("name");
        System.out.println(name);
        System.out.println("---------");

        //获取所有参数名称值
        Enumeration<String> names = config.getInitParameterNames();
        while (names.hasMoreElements()){
            String key = names.nextElement();
            String value = config.getInitParameter(key);
            System.out.println(key+"---"+value);
        }
        System.out.println("---------");

        //获取Servlet名称
        String servletName = config.getServletName();
        System.out.println(servletName);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
